﻿using Fluffy.Library.FileSources;
using Fluffy.Library.Utils;
using SevenZip;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;

namespace Fluffy.Archive
{
	internal class ArchiveDocumentModel
    {
		private readonly IFile _file;
		private readonly IList<ArchiveFileInfo> _filesNames = new ArchiveFileInfo[0];

		public ArchiveDocumentModel(IFile file)
	    {
		    if (file == null) 
				throw new ArgumentNullException("file");

		    _file = file;

			string libName = Environment.Is64BitOperatingSystem ? "7z64.dll" : "7z.dll";
			SevenZipBase.SetLibraryPath(Path.Combine(PathUtils.AppBinaryPath, libName));

			// TODO: dispose this instanse
			SevenZipExtractor extractor = new SevenZipExtractor(_file.FilePath);
			_filesNames = new ReadOnlyCollection<ArchiveFileInfo>(extractor.ArchiveFileData);	
	    }

		internal IList<ArchiveFileInfo> FilesNames
		{
			get { return _filesNames; }
		}
		
		internal string ArchiveName
		{
			get { return _file.FileName; }
		}

		public void Extract(ArchiveFileInfo info, string dir)
		{
			if (!Directory.Exists(dir))
				Directory.CreateDirectory(dir);

			using (SevenZipExtractor extractor = new SevenZipExtractor(_file.FilePath))
			{
				using (FileStream file = File.Create(Path.Combine(dir, Path.GetFileName(info.FileName))))
				{
					extractor.ExtractFile(info.Index, file);
				}
			}
		}

		public void ExtractIntoStreamAsync(ArchiveFileInfo info, Stream buffer)
		{
			SevenZipExtractor extractor = new SevenZipExtractor(_file.FilePath);
			extractor.FileExtractionFinished += (s, e) => extractor.Dispose();
			extractor.BeginExtractFile(info.Index, buffer);
		}
    }
}
